<script setup>
/**
 * 企业端减员报送表单
 * - 加载减员类型/原因字典
 * - 选期次后拉取企业报表数据
 * - 支持暂存、提交，并做前端校验
 */
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import {
  InfoFilled,
  ArrowLeft,
  Clock,
  User,
  UserFilled,
  WarningFilled,
  Right,
} from '@element-plus/icons-vue';
// import AppSidebar from '@/components/common/AppSidebar.vue';
import { useRoute, useRouter } from 'vue-router';
import {
  fetchReport,
  fetchReportById,
  saveDraft,
  submitReport,
  resubmitReport,
  fetchReductionTypes,
  fetchReasons,
  fetchAuditHistory,
  fetchCurrentPeriods,
  fetchReportHistory,
} from '@/api/report';

// 获取路由实例
const route = useRoute();
const router = useRouter();

/**
 * 常量配置
 */
const OTHER_CODE = 'OTHER'; // 若后端把“其他”编码成别的值，这里同步调整
const MAX_EMPLOYEES = 999_999_999; // 人数输入上限：防止异常大值导致接口错误
const statusConfig = {
  '-1': { label: '未填报', type: 'info' },
  0: { label: '已暂存', type: 'warning' },
  1: { label: '待市级审核', type: 'warning' },
  2: { label: '待省级审核', type: 'primary' },
  3: { label: '审核通过', type: 'success' },
  4: { label: '已归档', type: 'info' },
  5: { label: '驳回', type: 'danger' },
};

/**
 * 工具：返回一份“干净”的默认表单对象。
 * 使用函数而不是常量，方便 reset 时复用，避免响应式引用被覆盖。
 */
const createDefaultForm = () => ({
  id: null,
  enterprise_id: null,
  reporting_period: '',
  status: '',
  initial_employees: null,
  current_employees: null,
  reduction_type_code: '',
  reduction_type_desc: '',
  primary_reason_code: '',
  secondary_reason_code: '',
  tertiary_reason_code: '',
  primary_reason_desc: '',
  secondary_reason_desc: '',
  tertiary_reason_desc: '',
  submitted_at: '',
  updated_at: '',
  editable: true,
  can_resubmit: false,
});

/**
 * 表单、状态、字典数据：全部响应式，供 Element Plus 和模板使用
 */
const form = reactive(createDefaultForm());
const formRef = ref(null); // 提交/暂存时触发表单校验
const loadingDictionaries = ref(false); // 字典加载遮罩
const loadingReport = ref(false); // 期次报表加载遮罩
const saving = ref(false); // 暂存按钮 loading
const submitting = ref(false); // 提交按钮 loading
const reductionTypes = ref([]); // 减员类型字典缓存
const reductionReasons = ref([]); // 减员原因字典缓存
const auditHistory = ref([]); // 审核历史列表
const showAuditHistory = ref(false); // 是否显示审核历史弹窗
const availablePeriods = ref([]); // 可填报的调查期列表
const showHistoryDialog = ref(false); // 版本历史弹窗
const selectedPeriodHistory = ref([]); // 当前期次的历史版本
const auditHistoryByReportId = ref({}); // 审核记录索引

// 添加新的响应式状态
const isInitialEmployeesLocked = ref(false); // 建档期就业人数是否锁定
const isCurrentEmployeesLocked = ref(false); // 调查期就业人数是否锁定
const isPeriodLocked = ref(false);

/**
 * 混合型状态/派生数据
 */
// 仅在加载报表数据时阻塞页面，避免字典加载阶段无法输入
const loading = computed(() => loadingReport.value);
const isOtherType = computed(() => form.reduction_type_code === OTHER_CODE); // 当前减员类型是不是“其他”
const isReadOnly = computed(() => form.editable === false);
const readonlyMessage = computed(() => {
  if (!isReadOnly.value) {
    return '';
  }
  if (['1', '2'].includes(form.status)) {
    return '报表已提交审核，当前版本仅供查看。';
  }
  if (['3', '4'].includes(form.status)) {
    return '报表已审核完成或归档，数据不可修改。';
  }
  if (form.status === '5' && !form.can_resubmit) {
    return '该版本已存在后续提交，仅保留为历史记录。';
  }
  return '该报表目前不可编辑。';
});

// 是否存在减员（建档期人数 > 调查期人数）
const hasReduction = computed(() => {
  return typeof form.initial_employees === 'number' &&
    typeof form.current_employees === 'number' &&
    form.current_employees < form.initial_employees;
});

/**
 * 判断原因是否“其他”：模板多处要用，写成纯函数即可
 */
const isOtherReason = (code) => code === OTHER_CODE;

/**
 * 原因下拉选项：
 * - primary: 全量
 * - secondary: 过滤掉主要原因
 * - tertiary: 过滤掉主要原因 + 次要原因
 */
const reasonOptions = computed(() => {
  const list = Array.isArray(reductionReasons.value) ? reductionReasons.value : [];
  return {
    primary: list,
    secondary: list.filter((item) => item.value !== form.primary_reason_code),
    tertiary: list.filter(
      (item) =>
        item.value !== form.primary_reason_code && item.value !== form.secondary_reason_code,
    ),
  };
});

/**
 * 减少人数展示：初始/当前均为数字时才计算
 */
const reductionCount = computed(() => {
  if (typeof form.initial_employees !== 'number' || typeof form.current_employees !== 'number') {
    return null;
  }
  return form.initial_employees - form.current_employees;
});

/**
 * 格式化调查期显示：将 "2025-Q4" 转换为 "2025年Q4"
 */
const formattedPeriod = computed(() => {
  if (!form.reporting_period) return '';
  // 支持格式：2025-Q4、2025-10、2025-02 等
  const period = form.reporting_period;

  // 如果包含 Q，说明是季度格式
  if (period.includes('Q')) {
    return period.replace('-', '年');
  }

  // 如果是月份格式（如 2025-10），转换为 2025年10月
  const match = period.match(/^(\d{4})-(\d{1,2})$/);
  if (match) {
    return `${match[1]}年${match[2]}月`;
  }

  // 其他情况直接返回原值
  return period;
});

/**
 * Element Plus 表单校验规则
 * - 部分规则依赖实时状态，因此写成函数 validator
 * - "其他"说明通过 validator 判断是否必填
 */
const rules = reactive({
  reporting_period: [{ required: true, message: '请选择报送期次', trigger: 'change' }],
  initial_employees: [
    { required: true, message: '请填写建档期就业人数', trigger: ['blur', 'change'] },
    {
      validator: (_, value, callback) => {
        if (value == null || value < 0) {
          callback(new Error('建档期人数不能为负数'));
          return;
        }
        callback();
      },
      trigger: ['blur', 'change'],
    },
  ],
  current_employees: [
    { required: true, message: '请填写调查期就业人数', trigger: ['blur', 'change'] },
    {
      validator: (_, value, callback) => {
        if (value == null || value < 0) {
          callback(new Error('调查期人数不能为负数'));
          return;
        }
        callback();
      },
      trigger: ['blur', 'change'],
    },
  ],
  reduction_type_code: [
    {
      validator: (_, value, callback) => {
        // 只有当调查期人数小于建档期人数时，才要求必填
        if (hasReduction.value && !value) {
          callback(new Error('当调查期人数小于建档期人数时，请选择减员类型'));
          return;
        }
        callback();
      },
      trigger: 'change',
    },
  ],
  reduction_type_desc: [
    {
      validator: (_, value, callback) => {
        if (isOtherType.value && !value?.trim()) {
          callback(new Error('选择“其他”时，请补充减员类型说明'));
          return;
        }
        callback();
      },
      trigger: 'blur',
    },
  ],
  primary_reason_code: [
    {
      validator: (_, value, callback) => {
        // 只有当调查期人数小于建档期人数时，才要求必填
        if (hasReduction.value && !value) {
          callback(new Error('当调查期人数小于建档期人数时，请选择主要原因'));
          return;
        }
        callback();
      },
      trigger: 'change',
    },
  ],
  primary_reason_desc: [
    {
      validator: (_, value, callback) => {
        // 只要选择了主要原因，说明就是必填的
        if (form.primary_reason_code && !value?.trim()) {
          callback(new Error('请填写主要原因说明'));
          return;
        }
        callback();
      },
      trigger: 'blur',
    },
  ],
  secondary_reason_desc: [
    {
      validator: (_, value, callback) => {
        // 只要选择了次要原因，说明就是必填的
        if (form.secondary_reason_code && !value?.trim()) {
          callback(new Error('请填写次要原因说明'));
          return;
        }
        callback();
      },
      trigger: 'blur',
    },
  ],
  tertiary_reason_desc: [
    {
      validator: (_, value, callback) => {
        // 只要选择了第三原因，说明就是必填的
        if (form.tertiary_reason_code && !value?.trim()) {
          callback(new Error('请填写第三原因说明'));
          return;
        }
        callback();
      },
      trigger: 'blur',
    },
  ],
});

/**
 * 重置表单到初始状态
 */
const resetForm = () => {
  Object.assign(form, createDefaultForm());
  isInitialEmployeesLocked.value = false;  // 重置锁定状态
  isCurrentEmployeesLocked.value = false;
  isPeriodLocked.value = false;
};

/**
 * 把接口返回的数据填充到 form 中（只覆盖已存在字段）
 */
const assignForm = (payload = {}) => {
  console.log('🔍 assignForm 接收到的完整数据:', JSON.stringify(payload, null, 2));
  console.log('🔍 is_initial_employees_locked 字段值:', payload.is_initial_employees_locked);
  console.log('🔍 initial_employees 字段值:', payload.initial_employees);

  Object.entries(payload).forEach(([key, value]) => {
    if (key in form) {
      form[key] = value;
      if (key === 'initial_employees' || key === 'is_initial_employees_locked') {
        console.log(`  ✅ 设置字段 ${key} = ${value}`);
      }
    }
  });

  // 新增：处理锁定状态
  if (payload.is_initial_employees_locked !== undefined) {
    isInitialEmployeesLocked.value = payload.is_initial_employees_locked;
    console.log('✅ 设置建档期锁定状态:', isInitialEmployeesLocked.value);
  } else {
    console.log('⚠️ 未找到 is_initial_employees_locked 字段');
  }

  if (route.query.editable === '0') {
    form.editable = false;
  }

  if (!form.editable) {
    isInitialEmployeesLocked.value = true;
    isCurrentEmployeesLocked.value = true;
    isPeriodLocked.value = true;
  }

  // 新增：处理调查期就业人数锁定状态
  if (payload.is_current_employees_locked !== undefined) {
    isCurrentEmployeesLocked.value = payload.is_current_employees_locked;
    console.log('✅ 设置调查期锁定状态:', isCurrentEmployeesLocked.value);
  } else {
    console.log('⚠️ 未找到 is_current_employees_locked 字段');
  }

  console.log('📝 最终表单状态:', {
    initial_employees: form.initial_employees,
    initial_locked: isInitialEmployeesLocked.value,
    current_employees: form.current_employees,
    current_locked: isCurrentEmployeesLocked.value
  });
};

/**
 * 拉取减员类型/原因字典：组件初始化时调用一次
 */
const loadDictionaries = async () => {
  loadingDictionaries.value = true;
  try {
    const [types, reasons] = await Promise.all([fetchReductionTypes(), fetchReasons()]);

    reductionTypes.value = Array.isArray(types)
      ? types.map((item) => ({
        value: item.value ?? '',
        label: item.label ?? item.value ?? '',
        description: item.description ?? '',
      }))
      : [];

    reductionReasons.value = Array.isArray(reasons)
      ? reasons.map((item) => ({
        value: item.value ?? '',
        label: item.label ?? item.value ?? '',
        description: item.description ?? '',
      }))
      : [];
  } catch (error) {
    ElMessage.error(error?.message || '减员类型/原因字典加载失败，请稍后再试');
  } finally {
    loadingDictionaries.value = false;
  }
};

/**
 * 格式化调查期文本显示（用于下拉列表）
 */
const formatInvestigateTime = (investigateTime) => {
  if (!investigateTime) return '';

  // 如果包含 Q，说明是季度格式（如 2025-Q4）
  if (investigateTime.includes('Q')) {
    return investigateTime.replace('-', '年');
  }

  // 如果是月份格式（如 2025-10），转换为 2025年10月
  const match = investigateTime.match(/^(\d{4})-(\d{1,2})$/);
  if (match) {
    return `${match[1]}年${match[2]}月`;
  }

  // 其他情况直接返回原值
  return investigateTime;
};

/**
 * 加载可填报的调查期列表
 */
const loadAvailablePeriods = async () => {
  try {
    const data = await fetchCurrentPeriods();
    availablePeriods.value = (data?.periods || []).map(period => {
      const rangeText = formatPeriodRange(period.period_start_time, period.period_end_time);
      return {
        value: period.investigate_time,
        label: rangeText,
        investigate_time: period.investigate_time,
        investigate_time_formatted: formatInvestigateTime(period.investigate_time),
        period_id: period.period_id,
        start_time: period.period_start_time,
        end_time: period.period_end_time,
        display: rangeText,
      };
    });
  } catch (error) {
    console.error('加载调查期失败:', error);
    availablePeriods.value = [];
  }
};

/**
 * 格式化调查期时间范围显示
 */
const formatPeriodRange = (startTime, endTime) => {
  if (!startTime || !endTime) return '';
  const toText = (dateLike) => {
    const date = new Date(dateLike);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
  };
  return `${toText(startTime)} - ${toText(endTime)}`;
};

const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};

const resolveReportId = (report) => {
  if (!report || typeof report !== 'object') return null;
  return report.id ?? report.report_id ?? report.reportId ?? null;
};

const getTimelineType = (row) => {
  const status = String(row?.status ?? '');
  if (status === '3' || status === '4') return 'success';
  if (status === '5') return 'danger';
  if (status === '2') return 'primary';
  if (status === '1') return 'warning';
  return 'info';
};

const getTimelineColor = (type) => {
  const map = {
    success: '#10b981',
    danger: '#ef4444',
    primary: '#3b82f6',
    warning: '#f97316',
    info: '#94a3b8',
  };
  return map[type] || '#94a3b8';
};

/**
 * 选中报送期次后加载报表数据
 * - 未选期次：直接重置表单
 * - 有期次：先重置，再灌入接口返回的数据
 */
const loadReport = async (period, id = null) => {
  if (!period) {
    resetForm();
    auditHistory.value = [];
    auditHistoryByReportId.value = {};
    selectedPeriodHistory.value = [];
    return;
  }

  loadingReport.value = true;
  try {
    console.log('🚀 开始加载报表数据，期次:', period, 'ID:', id);

    let data;
    if (id) {
      data = await fetchReportById(id);
    } else {
      data = await fetchReport({ reporting_period: period });
    }

    console.log('📊 API返回的原始数据:', data);
    console.log('📊 数据类型:', typeof data);
    console.log('📊 initial_employees:', data?.initial_employees);
    console.log('📊 is_initial_employees_locked:', data?.is_initial_employees_locked);

    resetForm();
    selectedPeriodHistory.value = [];
    auditHistoryByReportId.value = {};

    if (data) {
      console.log('🔄 开始回填数据到表单');
      assignForm(data);
      console.log('✅ 回填后的表单 initial_employees:', form.initial_employees);
      console.log('✅ 回填后的锁定状态:', isInitialEmployeesLocked.value);

      if (data.id || data.editable === false) {
        isPeriodLocked.value = true;
      }

      if (form.editable === false) {
        isInitialEmployeesLocked.value = true;
        isCurrentEmployeesLocked.value = true;
      }
    }

    form.reporting_period = period;

    if (period && !availablePeriods.value.some(p => p.value === period)) {
      const displayTime = formatInvestigateTime(period);
      const rangeText = (data?.period_start_time && data?.period_end_time)
        ? formatPeriodRange(data.period_start_time, data.period_end_time)
        : displayTime;

      availablePeriods.value.push({
        value: period,
        label: rangeText,
        display: rangeText,
        investigate_time_formatted: displayTime,
      });
    }

    // 如果报表状态是驳回（5），自动加载审核历史
    if (data && data.status === '5') {
      await loadAuditHistory(period);
    }
  } catch (error) {
    console.error('❌ 加载报表失败:', error);
    ElMessage.error(error?.message || '报表数据加载失败，请稍后再试');
  } finally {
    loadingReport.value = false;
  }
};

/**
 * 加载审核历史
 */
const loadAuditHistory = async (period) => {
  if (!period) return;

  try {
    const data = await fetchAuditHistory({ reporting_period: period });
    auditHistory.value = data.audit_history || [];
    buildAuditIndex(data?.audit_history || []);
  } catch (error) {
    console.error('加载审核历史失败:', error);
    auditHistory.value = [];
  }
};

/**
 * 查看审核历史（点击按钮）
 */
const handleViewAuditHistory = async () => {
  if (!form.reporting_period) {
    ElMessage.warning('请先选择报送期次');
    return;
  }

  await loadAuditHistory(form.reporting_period);
  showAuditHistory.value = true;
};

/**
 * 返回报表列表
 */
const handleGoBack = () => {
  router.push('/report/list');
};

const formatAuditTime = (timeStr) => {
  if (!timeStr) return '-';
  if (timeStr.includes('T')) {
    return formatDate(timeStr);
  }
  return timeStr;
};

const seedAuditSnapshots = (reports = []) => {
  const next = { ...auditHistoryByReportId.value };
  reports.forEach((report) => {
    const reportId = resolveReportId(report);
    if (!report || !reportId) return;

    if (
      report.latest_audit_level == null &&
      report.latest_audit_result == null &&
      !report.latest_audit_opinion &&
      !report.latest_audit_time
    ) {
      return;
    }

    const snapshot = {
      audit_level: report.latest_audit_level,
      audit_level_name: report.latest_audit_level_name,
      audit_result: report.latest_audit_result,
      audit_result_name: report.latest_audit_result_name,
      audit_opinion: report.latest_audit_opinion,
      audit_time: report.latest_audit_time,
    };

    next[reportId] = {
      latest: snapshot,
      latestReject: report.latest_audit_result === 2 ? snapshot : null,
    };
  });
  auditHistoryByReportId.value = next;
};

const buildAuditIndex = (historyList = []) => {
  const map = {};
  historyList.forEach((item) => {
    const reportId = item.report_id;
    if (!reportId) return;
    if (!map[reportId]) map[reportId] = [];
    map[reportId].push(item);
  });

  const result = {};
  Object.keys(map).forEach((reportId) => {
    const sorted = map[reportId]
      .filter((record) => record.audit_time)
      .sort((a, b) => new Date(b.audit_time) - new Date(a.audit_time));
    const latestReject = sorted.find((record) => record.audit_result === 2);
    result[reportId] = {
      latest: sorted[0] || null,
      latestReject,
    };
  });

  const merged = { ...auditHistoryByReportId.value };
  Object.keys(result).forEach((reportId) => {
    const snapshot = result[reportId];
    if (!merged[reportId]) {
      merged[reportId] = snapshot;
      return;
    }
    merged[reportId] = {
      latest: snapshot.latest || merged[reportId].latest,
      latestReject: snapshot.latestReject || merged[reportId].latestReject,
    };
  });
  auditHistoryByReportId.value = merged;
};

const getRejectInfo = (row) => {
  const fallback = {
    department: row?.latest_audit_level_name || '-',
    reason: row?.latest_audit_opinion || '-',
    time: row?.latest_audit_time ? formatAuditTime(row.latest_audit_time) : '-',
  };

  const rowId = resolveReportId(row);
  const info = rowId ? auditHistoryByReportId.value[rowId] : null;
  if (!info || !info.latestReject) {
    return fallback;
  }
  const { latestReject } = info;
  return {
    department: latestReject.audit_level_name || latestReject.audit_level || fallback.department,
    reason: latestReject.audit_opinion || fallback.reason,
    time: latestReject.audit_time ? formatAuditTime(latestReject.audit_time) : fallback.time,
  };
};

const historyTimelineData = computed(() => {
  return (selectedPeriodHistory.value || []).map((item, index) => {
    const rejectInfo = getRejectInfo(item);
    const statusKey = String(item?.status ?? '');
    const statusMeta = statusConfig[statusKey] || {};
    const rejectSection = item?.reason_return || item?.reasonReturn || '';
    const isRejectedStatus = statusKey === '5';

    return {
      ...item,
      __key: resolveReportId(item) || `${item.reporting_period}-${index}`,
      __statusLabel: statusMeta.label || statusKey,
      __statusType: statusMeta.type || 'info',
      __timelineType: getTimelineType(item),
      __rejectInfo: rejectInfo,
      __showReject: isRejectedStatus,
      __rejectSection: rejectSection,
    };
  });
});

const handleViewHistory = async () => {
  if (!form.reporting_period) {
    ElMessage.warning('请先选择报送期次');
    return;
  }
  try {
    const history = await fetchReportHistory({ reporting_period: form.reporting_period });
    const normalized = (history || [])
      .sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
      .map((report, index) => ({
        ...report,
        rowNo: index + 1,
        fill_time: formatDate(report.updated_at),
        period_range: formatPeriodRange(report.period_start_time, report.period_end_time),
      }));
    selectedPeriodHistory.value = normalized;
    seedAuditSnapshots(normalized);
    await loadAuditHistory(form.reporting_period);
    showHistoryDialog.value = true;
  } catch (error) {
    ElMessage.error(error?.message || '加载历史版本失败');
  }
};

const handleViewSnapshot = (item) => {
  showHistoryDialog.value = false;
  form.reporting_period = item.reporting_period;
  loadReport(item.reporting_period, resolveReportId(item));
};

/**
 * 原因选择联动：
 * - 防止主/次/第三原因重复
 * - 清空上级原因时，自动清空下级原因
 */
const handleReasonChange = (level, value) => {
  if (level === 'primary') {
    // 如果清空主要原因，同时清空次要和第三原因
    if (!value) {
      form.secondary_reason_code = '';
      form.secondary_reason_desc = '';
      form.tertiary_reason_code = '';
      form.tertiary_reason_desc = '';
      return;
    }

    // 如果主要原因与次要原因重复，清空次要原因
    if (value === form.secondary_reason_code) {
      form.secondary_reason_code = '';
      form.secondary_reason_desc = '';
    }
    // 如果主要原因与第三原因重复，清空第三原因
    if (value === form.tertiary_reason_code) {
      form.tertiary_reason_code = '';
      form.tertiary_reason_desc = '';
    }
    return;
  }

  if (level === 'secondary') {
    // 如果清空次要原因，同时清空第三原因
    if (!value) {
      form.tertiary_reason_code = '';
      form.tertiary_reason_desc = '';
      return;
    }

    // 次要原因不能与主要原因相同
    if (value === form.primary_reason_code) {
      form.secondary_reason_code = '';
      ElMessage.warning('次要原因不能与主要原因相同');
      return;
    }
    // 如果次要原因与第三原因重复，清空第三原因
    if (value === form.tertiary_reason_code) {
      form.tertiary_reason_code = '';
      form.tertiary_reason_desc = '';
    }
    return;
  }

  // 第三原因
  if (value && (value === form.primary_reason_code || value === form.secondary_reason_code)) {
    form.tertiary_reason_code = '';
    ElMessage.warning('第三原因不能与前两项原因重复');
    return;
  }
};

/**
 * 监听减员类型：如果不再是“其他”，清空说明字段
 */
watch(
  () => form.reduction_type_code,
  (code) => {
    if (!isOtherReason(code)) {
      form.reduction_type_desc = '';
    }
  },
);

// 监听是否有减员：无减员时强制清空所有减员相关字段
watch(
  hasReduction,
  (val) => {
    if (!val) {
      form.reduction_type_code = '';
      form.reduction_type_desc = '';
      form.primary_reason_code = '';
      form.primary_reason_desc = '';
      form.secondary_reason_code = '';
      form.secondary_reason_desc = '';
      form.tertiary_reason_code = '';
      form.tertiary_reason_desc = '';
    }
  },
  { immediate: true },
);

/**
 * 监听调查期就业人数：如果建档期人数未锁定（说明无历史数据），则自动同步
 * 实现：若没有上期报表，建档期就业人数 = 调查期就业人数
 */
watch(
  () => form.current_employees,
  (newVal) => {
    if (!isInitialEmployeesLocked.value) {
      form.initial_employees = newVal;
    }
  }
);

/**
 * 构建接口需要的纯对象数据（避开 reactive 的响应式代理）
 */
const buildPayload = () => JSON.parse(JSON.stringify(form));

/**
 * 暂存草稿：前端做最基本校验（必须选期次）
 */
const handleSaveDraft = async () => {
  if (isReadOnly.value) {
    ElMessage.warning('当前报表已锁定，无法暂存草稿');
    return;
  }
  if (!form.reporting_period) {
    ElMessage.warning('请选择报送期次后再暂存草稿');
    return;
  }

  try {
    saving.value = true;
    await saveDraft(buildPayload());
    ElMessage.success('草稿已保存');
  } catch (error) {
    ElMessage.error(error?.message || '草稿保存失败，请重试');
  } finally {
    saving.value = false;
  }
};

/**
 * 正式提交：
 * - 先触发 Element Plus 表单校验
 * - 根据状态判断是普通提交还是重新提交
 * - 提交成功重新拉取最新报表
 */
const handleSubmit = async () => {
  if (!formRef.value) return;

  if (isReadOnly.value) {
    ElMessage.warning('当前报表已锁定，无法提交');
    return;
  }

  try {
    submitting.value = true;
    await formRef.value.validate();

    // 判断是普通提交还是重新提交（status=5是驳回状态）
    if (form.can_resubmit) {
      await resubmitReport(buildPayload());
      ElMessage.success('重新提交成功，等待审核');
    } else {
      await submitReport(buildPayload());
      ElMessage.success('报表已提交，等待市级审核');
    }

    await loadReport(form.reporting_period);
  } catch (error) {
    // 表单校验失败时不会有 message，这里只提示接口错误
    if (error?.message) {
      ElMessage.error(error.message);
    }
  } finally {
    submitting.value = false;
  }
};

/**
 * 组件初始化：加载字典、可填报调查期，并检查 URL 参数
 */
onMounted(async () => {
  await loadDictionaries();
  await loadAvailablePeriods();

  // 如果 URL 中有 period 参数，自动加载该期次的数据
  const periodFromQuery = route.query.period;
  const idFromQuery = route.query.id;

  if (periodFromQuery) {
    form.reporting_period = periodFromQuery;
    await loadReport(periodFromQuery, idFromQuery);
  }
});
</script>

<template>
  <div class="report-form">
    <!-- 左侧固定导航 -->
    <!-- <AppSidebar /> -->

    <!-- 右侧主内容，加上 v-loading 在加载字典/报表时显示遮罩 -->
    <el-main class="report-main" v-loading="loading">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="header-content">
          <el-button :icon="ArrowLeft" @click="handleGoBack" class="back-btn" round>
            返回
          </el-button>
          <div class="header-text">
            <h1 class="page-title">数据填报</h1>
            <p class="page-subtitle">填写企业就业失业数据报表</p>
          </div>
        </div>
      </div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="140px" status-icon scroll-to-error
        class="report-form-content">
        <!-- 基本信息 -->
        <section class="form-section">
          <div class="section-header">
            <h3 class="section-title">基本信息</h3>
            <p class="section-desc">填写报送期次和就业人数</p>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报送期次" prop="reporting_period">
                <el-select v-model="form.reporting_period" placeholder="请选择报送期次" @change="loadReport" clearable
                  :disabled="isPeriodLocked || isReadOnly">
                  <el-option v-for="period in availablePeriods" :key="period.value" :label="period.label"
                    :value="period.value">
                    <div class="period-option-inline">
                      <span class="period-label">{{ period.display }}</span>
                      <span class="period-range-inline">调查期：{{ period.investigate_time_formatted }}</span>
                    </div>
                  </el-option>
                </el-select>
                <div v-if="isPeriodLocked" class="field-hint">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                  <span>编辑已有报表时，报送期次不可修改</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="调查期">
                <el-input :value="formattedPeriod" readonly placeholder="选择报送期次后自动显示" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="form.reporting_period">
            <el-col :span="12">
              <el-form-item label="建档期就业人数" prop="initial_employees">
                <el-input-number v-model="form.initial_employees" :min="0" :max="MAX_EMPLOYEES" :controls="false"
                  :disabled="isInitialEmployeesLocked || isReadOnly" placeholder="自动填充" />
                <div v-if="isInitialEmployeesLocked" class="field-hint">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                  <span>该数据来自上一调查期，不可修改</span>
                </div>
                <div v-else class="field-hint">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                  <span>由于你是第一次填报数据，只需要填写此调查期的人数即可。</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="调查期就业人数" prop="current_employees">
                <el-input-number v-model="form.current_employees" :min="0" :max="MAX_EMPLOYEES" :controls="false"
                  :disabled="isCurrentEmployeesLocked || isReadOnly" placeholder="请输入人数" />
                <!-- 添加提示信息 -->
                <div v-if="isCurrentEmployeesLocked" class="field-hint">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                  <span>编辑已有报表时，调查期就业人数不可修改</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 减少人数提示 -->
          <el-alert v-if="reductionCount !== null" class="reduction-summary" type="info" show-icon :closable="false"
            :title="`本期${reductionCount >= 0 ? '减少' : '增加'}人数：${Math.abs(reductionCount)} 人`"
            description="人数变化 = 建档期人数 - 调查期人数；若建档期人数大于调查期人数则为减员，需填写减员信息" />
        </section>

        <!-- 减员类型 -->
        <section class="form-section" v-if="hasReduction">
          <div class="section-header">
            <h3 class="section-title">减员类型</h3>
            <p class="section-desc">选择减员类型及说明</p>
          </div>
          <el-form-item label="减员类型" prop="reduction_type_code">
            <el-select v-model="form.reduction_type_code" placeholder="请选择减员类型" clearable :disabled="isReadOnly">
              <el-option v-for="item in reductionTypes" :key="item.value" :label="item.label" :value="item.value">
                <span>{{ item.label }}</span>
                <el-tooltip v-if="item.description" effect="dark" placement="right">
                  <template #content>{{ item.description }}</template>
                  <el-icon class="option-info">
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item v-if="isOtherType" label="其他类型说明" prop="reduction_type_desc">
            <el-input v-model="form.reduction_type_desc" type="textarea" maxlength="200" show-word-limit
              placeholder="选择「其他」时需说明具体减员类型" :disabled="isReadOnly" />
          </el-form-item>
        </section>

        <!-- 减员原因 -->
        <section class="form-section" v-if="hasReduction">
          <div class="section-header">
            <h3 class="section-title">减员原因</h3>
            <p class="section-desc">选择主要原因，可选填次要和第三原因</p>
          </div>
          <el-row :gutter="20">
            <!-- 主要原因 -->
            <el-col :span="8">
              <el-form-item label="主要原因" prop="primary_reason_code">
                <el-select v-model="form.primary_reason_code" placeholder="请选择主要原因" clearable
                  @change="(val) => handleReasonChange('primary', val)" :disabled="isReadOnly">
                  <el-option v-for="item in reasonOptions.primary" :key="item.value" :label="item.label"
                    :value="item.value">
                    <span>{{ item.label }}</span>
                    <el-tooltip v-if="item.description" effect="dark" placement="right">
                      <template #content>{{ item.description }}</template>
                      <el-icon class="option-info">
                        <InfoFilled />
                      </el-icon>
                    </el-tooltip>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="form.primary_reason_code" label="主要原因说明" prop="primary_reason_desc">
                <el-input v-model="form.primary_reason_desc" type="textarea" maxlength="200" show-word-limit
                  :placeholder="isOtherReason(form.primary_reason_code) ? '请写明具体是什么原因，以及原因说明' : '请填写原因说明'"
                  :disabled="isReadOnly" />
              </el-form-item>
            </el-col>

            <!-- 次要原因 -->
            <el-col :span="8" v-if="form.primary_reason_code">
              <el-form-item label="次要原因" prop="secondary_reason_code">
                <el-select v-model="form.secondary_reason_code" placeholder="可选" clearable
                  @change="(val) => handleReasonChange('secondary', val)" :disabled="isReadOnly">
                  <el-option v-for="item in reasonOptions.secondary" :key="item.value" :label="item.label"
                    :value="item.value">
                    <span>{{ item.label }}</span>
                    <el-tooltip v-if="item.description" effect="dark" placement="right">
                      <template #content>{{ item.description }}</template>
                      <el-icon class="option-info">
                        <InfoFilled />
                      </el-icon>
                    </el-tooltip>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="form.secondary_reason_code" label="次要原因说明" prop="secondary_reason_desc">
                <el-input v-model="form.secondary_reason_desc" type="textarea" maxlength="200" show-word-limit
                  :placeholder="isOtherReason(form.secondary_reason_code) ? '请写明具体是什么原因，以及原因说明' : '请填写原因说明'"
                  :disabled="isReadOnly" />
              </el-form-item>
            </el-col>

            <!-- 第三原因 -->
            <el-col :span="8" v-if="form.secondary_reason_code">
              <el-form-item label="第三原因" prop="tertiary_reason_code">
                <el-select v-model="form.tertiary_reason_code" placeholder="可选" clearable
                  @change="(val) => handleReasonChange('tertiary', val)" :disabled="isReadOnly">
                  <el-option v-for="item in reasonOptions.tertiary" :key="item.value" :label="item.label"
                    :value="item.value">
                    <span>{{ item.label }}</span>
                    <el-tooltip v-if="item.description" effect="dark" placement="right">
                      <template #content>{{ item.description }}</template>
                      <el-icon class="option-info">
                        <InfoFilled />
                      </el-icon>
                    </el-tooltip>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="form.tertiary_reason_code" label="第三原因说明" prop="tertiary_reason_desc">
                <el-input v-model="form.tertiary_reason_desc" type="textarea" maxlength="200" show-word-limit
                  :placeholder="isOtherReason(form.tertiary_reason_code) ? '请写明具体是什么原因，以及原因说明' : '请填写原因说明'"
                  :disabled="isReadOnly" />
              </el-form-item>
            </el-col>
          </el-row>
        </section>

        <el-alert v-if="isReadOnly" class="readonly-alert" type="info" show-icon :closable="false" title="当前报表已锁定"
          :description="readonlyMessage" />

        <!-- 审核历史提示（驳回状态时显示）-->
        <el-alert v-if="form.status === '5' && auditHistory.length > 0" type="error" title="报表已被驳回" :closable="false"
          class="reject-alert">
          <template #default>
            <div class="reject-content">
              <p><strong>驳回原因：</strong>{{ auditHistory[0].audit_opinion }}</p>
              <el-button size="small" @click="handleViewAuditHistory" link>
                查看完整审核历史 →
              </el-button>
            </div>
          </template>
        </el-alert>

        <!-- 操作按钮 -->
        <section class="section-actions">
          <el-button size="large" round @click="handleViewHistory" :disabled="!form.reporting_period">
            版本历史
          </el-button>
          <el-button v-if="auditHistory.length > 0 || form.status === '5'" size="large" round
            @click="handleViewAuditHistory">
            查看审核历史
          </el-button>
          <template v-if="!isReadOnly">
            <el-button size="large" round :loading="saving" @click="handleSaveDraft">
              暂存草稿
            </el-button>
            <el-button size="large" round type="primary" :loading="submitting" @click="handleSubmit">
              {{ form.can_resubmit ? '重新提交' : '提交报表' }}
            </el-button>
          </template>
        </section>
      </el-form>

      <!-- 审核历史弹窗 -->
      <el-dialog v-model="showAuditHistory" title="审核历史" width="700px" :close-on-click-modal="false">
        <el-timeline v-if="auditHistory.length > 0">
          <el-timeline-item v-for="(item, index) in auditHistory" :key="item.audit_id" :timestamp="item.audit_time"
            placement="top" :type="item.audit_result === 1 ? 'success' : 'danger'">
            <el-card>
              <template #header>
                <div class="audit-card-header">
                  <el-tag :type="item.audit_result === 1 ? 'success' : 'danger'" size="large">
                    {{ item.audit_result_name }}
                  </el-tag>
                  <span class="audit-level">{{ item.audit_level_name }}</span>
                </div>
              </template>
              <p class="audit-opinion">{{ item.audit_opinion }}</p>
              <p class="audit-auditor">审核人：{{ item.auditor }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂无审核记录" />
      </el-dialog>

      <!-- 历史版本弹窗 -->
      <el-dialog
        v-model="showHistoryDialog"
        title="历史版本记录"
        width="720px"
        :close-on-click-modal="false"
        class="history-dialog"
      >
        <div v-if="historyTimelineData.length" class="history-dialog-body">
          <el-timeline class="history-timeline">
            <el-timeline-item
              v-for="item in historyTimelineData"
              :key="item.__key"
              :type="item.__timelineType"
              :color="getTimelineColor(item.__timelineType)"
              placement="top"
              hide-timestamp
            >
              <div class="history-card">
                <div class="history-card__header">
                  <div class="history-time-badge">
                    <el-icon>
                      <clock />
                    </el-icon>
                    <span>{{
                      item.submitted_at ? formatDate(item.submitted_at) : '未提交 / 草稿'
                    }}</span>
                  </div>
                  <el-tag
                    :type="item.__statusType"
                    effect="dark"
                    round
                    size="small"
                    style="font-weight: 600; border: none"
                  >
                    {{ item.__statusLabel }}
                  </el-tag>
                </div>

                <div class="history-card__body">
                  <div class="history-metrics">
                    <div class="metric-item">
                      <div class="metric-icon-box">
                        <el-icon>
                          <user />
                        </el-icon>
                      </div>
                      <div class="metric-content">
                        <span class="metric-label">建档期人数</span>
                        <span class="metric-value">{{ item.initial_employees ?? '-' }}</span>
                      </div>
                    </div>

                    <div class="metric-separator"></div>

                    <div class="metric-item">
                      <div class="metric-icon-box">
                        <el-icon><user-filled /></el-icon>
                      </div>
                      <div class="metric-content">
                        <span class="metric-label">调查期人数</span>
                        <span class="metric-value">{{ item.current_employees ?? '-' }}</span>
                      </div>
                    </div>
                  </div>

                  <div v-if="item.__showReject" class="reject-zone">
                    <div class="reject-icon">
                      <el-icon><warning-filled /></el-icon>
                    </div>
                    <div class="reject-content">
                      <div class="reject-title">审核驳回</div>
                      <div class="reject-desc">
                        {{ item.__rejectInfo.reason }}
                      </div>
                      <div class="reject-meta">
                        {{ item.__rejectInfo.department }} •
                        {{ item.__rejectInfo.time }}
                      </div>
                    </div>
                  </div>
                </div>

                <div class="history-card__footer">
                  <span class="version-id"
                    >ID: {{ resolveReportId(item)?.toString().slice(-8) || '...' }}</span
                  >
                  <div class="view-snapshot-btn" @click="handleViewSnapshot(item)">
                    查看快照
                    <el-icon>
                      <right />
                    </el-icon>
                  </div>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
        <el-empty v-else description="暂无历史记录" />
      </el-dialog>
    </el-main>
  </div>
</template>

<style scoped lang="scss">
.report-form {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(160deg, #eef2ff 0%, #f8fafc 45%, #ffffff 100%);
  --card-radius-lg: 24px;
  --card-radius-md: 18px;
  --card-radius-sm: 14px;
}

.report-main {
  flex: 1;
  padding: 64px 72px 80px;
  overflow: auto;
  max-width: 1400px;
}

.page-header {
  margin-bottom: 40px;

  .header-content {
    display: flex;
    align-items: flex-start;
    gap: 16px;
  }

  .back-btn {
    flex-shrink: 0;
  }

  .header-text {
    flex: 1;
  }

  .page-title {
    font-size: 34px;
    font-weight: 700;
    color: var(--el-text-color-primary);
    letter-spacing: -0.02em;
    margin: 0 0 8px 0;
    line-height: 1.2;
  }

  .page-subtitle {
    font-size: 17px;
    color: var(--el-text-color-regular);
    margin: 0;
    letter-spacing: -0.01em;
  }
}

.report-form-content {
  max-width: 100%;
}

.form-section {
  position: relative;
  margin-bottom: 32px;
  padding: 36px 40px;
  background: rgba(255, 255, 255, 0.86);
  border-radius: var(--card-radius-lg);
  border: 1px solid rgba(148, 163, 184, 0.14);
  box-shadow:
    0 20px 45px rgba(15, 23, 42, 0.08),
    0 2px 6px rgba(15, 23, 42, 0.05);
  backdrop-filter: blur(22px);
  transition: transform 0.28s ease, box-shadow 0.28s ease;

  &::after {
    content: '';
    position: absolute;
    inset: 0;
    border-radius: inherit;
    background: linear-gradient(145deg, rgba(255, 255, 255, 0.35), rgba(255, 255, 255, 0));
    opacity: 0;
    transition: opacity 0.3s ease;
    pointer-events: none;
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow:
      0 28px 55px rgba(15, 23, 42, 0.12),
      0 4px 16px rgba(15, 23, 42, 0.05);

    &::after {
      opacity: 1;
    }
  }

  &:last-of-type {
    margin-bottom: 0;
  }
}

.section-header {
  margin-bottom: 28px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(226, 232, 240, 0.8);

  .section-title {
    font-size: 24px;
    font-weight: 650;
    color: #0f172a;
    letter-spacing: -0.02em;
    margin: 0 0 6px 0;
    line-height: 1.3;
  }

  .section-desc {
    font-size: 14px;
    color: #64748b;
    margin: 0;
    letter-spacing: -0.01em;
  }
}

.option-info {
  margin-left: 8px;
  color: var(--el-color-primary);
  cursor: help;
  transition: all 0.2s ease;

  &:hover {
    transform: scale(1.1);
  }
}

.reduction-summary {
  margin-top: 20px;
  border-radius: var(--card-radius-md);
  border: 1px solid rgba(59, 130, 246, 0.18);
  background: rgba(59, 130, 246, 0.12);

  :deep(.el-alert__icon) {
    color: var(--el-color-primary);
  }

  :deep(.el-alert__title) {
    color: #0f172a;
    font-weight: 500;
    letter-spacing: -0.01em;
  }

  :deep(.el-alert__description) {
    color: #1e293b;
    font-size: 13px;
    letter-spacing: -0.01em;
  }
}

.section-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 36px;
  padding-top: 28px;
  border-top: 1px solid rgba(226, 232, 240, 0.8);
}

// Element Plus 表单项样式优化
:deep(.el-form-item) {
  margin-bottom: 24px;

  .el-form-item__label {
    color: var(--el-text-color-primary);
    font-weight: 500;
    font-size: 14px;
    letter-spacing: -0.01em;
    line-height: 36px;
  }

  .el-input__wrapper,
  .el-textarea__inner {
    border-radius: var(--card-radius-sm);
    border: 1px solid var(--el-border-color);
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
    transition: all 0.2s ease;

    &:hover {
      border-color: var(--el-color-primary-light-5);
    }

    &.is-focus {
      border-color: var(--el-color-primary);
      box-shadow:
        0 0 0 3px var(--el-color-primary-light-9),
        0 2px 4px rgba(0, 0, 0, 0.02);
    }
  }

  .el-select {
    width: 100%;
  }

  .el-input-number {
    width: 100%;

    .el-input__wrapper {
      border-radius: var(--card-radius-sm);
    }
  }

  .el-date-editor {
    width: 100%;
  }
}

// 下拉选择器样式优化
:deep(.el-select-dropdown) {
  border-radius: var(--card-radius-md);
  border: 1px solid var(--el-border-color-light);
  box-shadow:
    0 4px 16px rgba(0, 0, 0, 0.08),
    0 2px 4px rgba(0, 0, 0, 0.04);

  .el-select-dropdown__item {
    border-radius: 8px;
    margin: 4px 8px;
    padding: 8px 12px;
    transition: all 0.2s ease;

    &:hover {
      background: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
    }

    &.selected {
      background: var(--el-color-primary-light-8);
      color: var(--el-color-primary);
      font-weight: 500;
    }
  }
}

// 调查期下拉选项样式（旧版，保留以防其他地方使用）
.period-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

// 调查期下拉选项样式（内联横向排列）
.period-option-inline {
  display: flex;
  align-items: center;
  gap: 12px;
}

.period-label {
  font-weight: 600;
  color: var(--el-text-color-primary);
  font-size: 14px;
}

.period-range {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.period-range-inline {
  font-size: 13px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
}

// 驳回提示框
.reject-alert {
  margin-bottom: 24px;
  border-radius: var(--card-radius-md);

  :deep(.el-alert__content) {
    width: 100%;
  }
}

.readonly-alert {
  margin-bottom: 24px;
}

.reject-content {
  p {
    margin: 0 0 8px 0;
    color: var(--el-text-color-primary);
  }
}

// 审核历史弹窗
.audit-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.audit-level {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.audit-opinion {
  margin: 12px 0;
  color: var(--el-text-color-primary);
  line-height: 1.6;
}

.audit-auditor {
  margin: 8px 0 0 0;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

// 响应式设计
@media (max-width: 1400px) {
  .report-main {
    padding: 40px 48px;
  }
}

@media (max-width: 1024px) {
  .report-main {
    padding: 32px 24px;
  }

  .form-section {
    padding: 24px;
  }

  .page-header .page-title {
    font-size: 28px;
  }
}

.field-hint {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  font-size: 12px;
  color: var(--el-color-info);

  .el-icon {
    font-size: 14px;
  }
}

// 禁用状态的输入框样式优化
:deep(.el-input-number.is-disabled) {
  .el-input__wrapper {
    background-color: var(--el-fill-color-light);
    cursor: not-allowed;
  }
}

.history-dialog :deep(.el-dialog) {
  border-radius: 24px;
  overflow: hidden;
  box-shadow: 0 40px 80px -20px rgba(0, 0, 0, 0.2);
}

.history-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 24px 32px;
  border-bottom: 1px solid #f1f5f9;
  background: #fff;
}

.history-dialog :deep(.el-dialog__title) {
  font-weight: 700;
  font-size: 18px;
  color: #0f172a;
}

.history-dialog-body {
  padding: 40px;
  max-height: 65vh;
  overflow-y: auto;
  background: #f8fafc;
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.history-dialog-body::-webkit-scrollbar {
  display: none;
}

.history-timeline {
  padding-left: 8px;
}

.history-timeline :deep(.el-timeline-item__node) {
  box-shadow: 0 0 0 4px white;
  width: 12px;
  height: 12px;
}

.history-timeline :deep(.el-timeline-item__tail) {
  border-left: 2px solid #e2e8f0;
  left: 5px;
  top: 14px;
  height: calc(100% - 14px);
}

.history-card {
  background: #ffffff;
  border-radius: 16px;
  box-shadow:
    0 4px 6px -1px rgba(0, 0, 0, 0.02),
    0 10px 15px -3px rgba(0, 0, 0, 0.02);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  margin-top: 0;
  border: 1px solid transparent;
}

.history-card:hover {
  transform: translateY(-3px);
  box-shadow:
    0 20px 25px -5px rgba(0, 0, 0, 0.05),
    0 8px 10px -6px rgba(0, 0, 0, 0.01);
  border-color: rgba(79, 70, 229, 0.1);
}

.history-card__header {
  padding: 16px 24px;
  border-bottom: 1px solid #f8fafc;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-time-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #64748b;
  font-weight: 500;
  background: #f8fafc;
  padding: 4px 10px;
  border-radius: 8px;
}

.history-time-badge .el-icon {
  font-size: 14px;
  color: #94a3b8;
}

.history-card__body {
  padding: 24px;
}

.history-metrics {
  display: flex;
  align-items: center;
}

.metric-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16px;
}

.metric-icon-box {
  width: 42px;
  height: 42px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  background: #eef2ff;
  color: #4f46e5;
  flex-shrink: 0;
}

.metric-content {
  display: flex;
  flex-direction: column;
}

.metric-label {
  font-size: 11px;
  color: #94a3b8;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.03em;
  margin-bottom: 4px;
}

.metric-value {
  font-size: 16px;
  font-weight: 700;
  color: #1e293b;
  font-variant-numeric: tabular-nums;
}

.metric-separator {
  width: 1px;
  height: 40px;
  background: #f1f5f9;
  margin: 0 32px;
}

.reject-zone {
  margin: 8px 0 0 0;
  background: #fff1f2;
  border-radius: 12px;
  padding: 16px;
  border: 1px solid #fecdd3;
  display: flex;
  gap: 12px;
}

.reject-icon {
  color: #e11d48;
  font-size: 20px;
  margin-top: 2px;
}

.reject-content {
  flex: 1;
}

.reject-title {
  color: #9f1239;
  font-weight: 700;
  font-size: 13px;
  margin-bottom: 4px;
}

.reject-desc {
  color: #be123c;
  font-size: 13px;
  line-height: 1.5;
}

.reject-meta {
  margin-top: 8px;
  font-size: 11px;
  color: #e11d48;
  opacity: 0.8;
  font-weight: 500;
}

.history-card__footer {
  background: #fcfcfc;
  padding: 12px 24px;
  border-top: 1px solid #f1f5f9;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.version-id {
  font-family: 'JetBrains Mono', monospace;
  font-size: 11px;
  color: #94a3b8;
}

.view-snapshot-btn {
  font-size: 13px;
  font-weight: 600;
  color: #4f46e5;
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  transition: gap 0.2s;
}

.view-snapshot-btn:hover {
  gap: 8px;
  color: #4338ca;
}
</style>
